//
//  TCPViewController.m
//  IOS_socketClient
//
//  Created by Maculish Ting on 15/5/6.
//  Copyright (c) 2015年 LYD. All rights reserved.
//  https://github.com/robbiehanson/CocoaAsyncSocket/wiki/Intro_GCDAsyncSocket

#import "TCPViewController.h"
#import "GCDAsyncSocket.h"

#define TAG_WELCOME 10
#define TAG_CAPABILITIES 11
#define TAG_MSG 12

NSUInteger length;   //总长度

@interface TCPViewController ()<GCDAsyncSocketDelegate>
{
    GCDAsyncSocket *tcpSocket;
    
    // ip地址 端口号
    NSString *addr;
    int portNum;
    
    BOOL isConnect;
}

@end

@implementation TCPViewController
@synthesize TcpImage;
@synthesize imageBuffer;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSocket];
    imageBuffer=[[NSMutableData alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)pressToConnect:(id)sender {

    addr=@"192.168.1.186";
    NSLog(@"%@",addr);
    [self connectSocket];
}

#pragma mark- setup  connect disconnect
- (void)setupSocket
{
    tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    // 初始化参数
    addr=[[NSString alloc] init];
    portNum=12321;
    isConnect=NO;
}

-(void)connectSocket
{
    if (tcpSocket.isDisconnected) {
        NSError *err = nil;
        if (![tcpSocket connectToHost:addr onPort:portNum error:&err]) // Asynchronous!
        {
            // If there was an error, it's likely something like "already connected" or "no delegate set"
            NSLog(@"I goofed: %@", err);
        }
        
        // At this point the socket is NOT connected.
        // But I can start writing to it anyway!
        // The library will queue all my write operations,
        // and after the socket connects, it will automatically start executing my writes!
        [self SendMessage:@"GetPicTest"];
        NSData *request1 = [@"FFFFGetPictText" dataUsingEncoding:NSUTF8StringEncoding];
//        NSData *request2 = [@"这是第2条消息啊" dataUsingEncoding:NSUTF8StringEncoding];
        
        
        // In fact, I know I have 2 requests.
        // Why not just get them both out of the way now?
//        [tcpSocket writeData:request2 withTimeout:-1 tag:2];
        [tcpSocket writeData:request1 withTimeout:-1 tag:0];
        
        /**
         * Reads the given number of bytes.
         *
         * If the timeout value is negative, the read operation will not use a timeout.
         *
         * If the length is 0, this method does nothing and the delegate is not called.
         **/
        NSUInteger responseHeaderLength=300;
//        [tcpSocket readDataToLength:responseHeaderLength withTimeout:-1 tag:TAG_WELCOME];

        //      read包头大小，tag
        [tcpSocket readDataWithTimeout:-1 tag:TAG_WELCOME];
        
        

        
    }else
    {
        [tcpSocket disconnect];
    }
}


//发送消息到server
-(void)SendMessage:(NSString*)sendMsg
{
    
    // 发送
    [tcpSocket writeData:[self formSendingMessage:sendMsg] withTimeout:-1 tag:0];
    [tcpSocket readDataWithTimeout:-1 tag:0];
    //    NSLog(@"Send message:%@",sendMsg);
}

// 组包
-(NSMutableData*)formSendingMessage:(NSString*)sendMsg
{
    NSData *head = [@"FFFF" dataUsingEncoding:NSUTF8StringEncoding];
    NSData *tail = [@"EEEE" dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [sendMsg dataUsingEncoding:NSUTF8StringEncoding];  //全部数据
    
    //命令
    int bufferlength = (int)(4+head.length+tail.length+data.length);  //总长度
    
    //命令总长度
    NSData *lengthbuffer = [NSData dataWithBytes:&bufferlength length:sizeof(int)];
    NSMutableData *buffer = [NSMutableData data];
    [buffer appendData:head];                //头部
    [buffer appendData:lengthbuffer];        //数据长度
//    [buffer appendData:commandBufferLength]; //命令长度
    [buffer appendData:data];                //全部数据
    [buffer appendData:tail];                //尾部
    
    return buffer;
}

- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"Cool, I'm connected! That was easy.");
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"disconnect %@",err);
}

#pragma mark- sendData
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if (tag == 2)
        NSLog(@"First request sent");
    else if (tag == 0)
        NSLog(@"Second request sent");
}

- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{

    
    //包总长
    NSInteger baoLeng = 0;
    [data getBytes:&baoLeng range:NSMakeRange(4,4)];
    //CMDLength
    NSInteger cmdLeng = 0;
    [data getBytes:&cmdLeng range:NSMakeRange(8, 4)];
    if (imageBuffer.length<627717) {
        [imageBuffer appendData:data];

    }
    
    NSLog(@"图片包长度%d",(int)imageBuffer.length);


    if (imageBuffer.length==627743) {
        NSData *buffer = [imageBuffer subdataWithRange:NSMakeRange(22,627717)];
        TcpImage.image= [UIImage imageWithData:buffer];
    }
    //有效数据长度
    
    [tcpSocket readDataWithTimeout:10 tag:0];//循环接受IP包
}


@end
